<?php
namespace Infinity;

class FormManager {

  private $form;
  private $form_state;

  public function __construct(&$form, &$form_state)
  {
    $this->form = &$form;
    $this->form_state = &$form;
  }

  public function hidden($key, $default_value=null) {
    if(!empty($this->form[$key])) {
      $this->form[$key]['#access'] = false;
      if($default_value)
        $this->form[$key]['#value'] = $default_value;
    }
  }

  public function hiddenTextFormat()
  {
    $js = 'jQuery(document).ready(function($) {
        $("#' . $this->form['#id'] . ' fieldset.filter-wrapper").hide();
      });';
    drupal_add_js($js, 'inline');
  }

  /*
  Infinity\Form::attachChainedSelects($tree, $form, array(
    'field_user_region_level1',
    'field_user_region_level2',
    'field_user_region'
  ));
  $form['field_user_region_level1']['#title'] = 'level1';
  $form['field_user_region_level2']['#title'] = 'level2';
  $form['field_user_region']['#title'] = 'level3';

  // default value
  $term_parents = Infinity\Term::getParents($default_tid);
  $form['field_user_region']['#default_value'] = $term_parents[0]->tid;
  $form['field_user_region_level2']['#default_value'] = $term_parents[1]->tid;
  $form['field_user_region_level1']['#default_value'] = $term_parents[2]->tid;
   */
  public function attachChainedSelects($taxonomy_tree, $keys=array(), $empty_label='- Select -', $index=0, $seed=0) {
    $key = $keys[$index];
    if($seed <= 0)
      $seed = rand(1, 999);
    $options = array('' => $empty_label);
    $attributes = array('' => array('class' => ''));
    foreach ($taxonomy_tree as $leaf) {
      if($leaf->depth == $index) {
        $parent = array_pop($leaf->parents);
        $options[$leaf->tid] = $leaf->name;
        $attributes[$leaf->tid] = array('class' => $parent);
      }
    }

    $this->form[$key] =array(
      '#type' => 'select',
      '#attributes' => array('id' => 'mark_'.$key.$seed),
      '#options' => $options,
      '#options_attributes' => $attributes,
      '#chained_selects' => array(
        'parent' => $index>0 ?'mark_'.$keys[$index-1].$seed : NULL,
        'child' => 'mark_'.$key.$seed,
      ),
    );

    if($index+1 < count($keys))
      self::attachChainedSelects($taxonomy_tree, $keys, $empty_label, $index+1, $seed);
  }
}